09. Simulate stock price trajectories

PRDTM2-787 AI Trading C4 L3 Vid8 Simulate Stock Price Trajectories

Programming the GBM Simulate Function

Creating a simulate function for the GBM model provides essential tools for testing trading algorithms against different market scenarios.

Function Elements Include:

  • N: Number of steps in each trajectory.
  • K: Total number of trajectories.
  • Dt: Time increment (Δt) per step.
  • S₀: Initial stock price.

Simulation Process:

  1. Trajectory Allocation

    • Use a 2D array with N+1 rows and K columns.
    • Initialize with "np.nan" values.
  2. Formula Application

    • Utilize the GBM formula adapting its components using the logarithm.
  3. Array Generation Using Linspace

    • Obtain a series: Δt, 2Δt, 3Δt, …
    • Multiply by (μ - \frac{σ^2}{2}) for adjustments.
  4. Brownian Motion Simulation

    • Generate n standard normal random variables.
    • Scale by Δt, and compute cumulative sums.
  5. Assembling

    • Combine terms into the exponential function argument.
    • Include initial price S₀ to initiate trajectories.

With these steps, price trajectories are successfully simulated, enabling scenario analysis for trading strategies.

QUESTION:

Generate a trajectory of a geometric Brownian motion with parameters mu = 0.4 and sigma = 0.5. The trajectory should include 200 prices with a time increment of 1/252 year. Start with the price equal to 1.

ANSWER:

import numpy as np
from scipy.stats import norm

mu = 0.4
sigma = 0.5
dt = 1/252
S0 = 1
n = 200

T = np.linspace(0, (n-1)*dt, n)
W = np.zeros(n)
W[1:] = np.cumsum(norm.rvs(size=n-1) * np.sqrt(dt))
X = np.exp((mu - sigma**2/2) * T + sigma * W)